package com.cangxuan.app.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.*;
import cn.jpush.android.api.JPushInterface;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.User;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;

import java.net.HttpURLConnection;

public class LoginActivity extends BaseActivity {


    TextView txtMobile;
    TextView txtVcode;
    Button btnSendVcode;
    LinearLayout layoutCountdown;
    TextView txtCountdown;
    CheckBox cbAgree;
    Button btnLogin;

    Handler handler = new Handler();

    Runnable reSendVcodeCountdownRunnable = new Runnable() {
        @Override
        public void run() {
            int second = Integer.parseInt(txtCountdown.getText().toString());   //获取原秒数
            if (second > 0) {
                txtCountdown.setText(String.valueOf(second - 1));
                //发起下一次本任务
                handler.postDelayed(reSendVcodeCountdownRunnable, 1000);
            } else {
                btnSendVcode.setVisibility(View.VISIBLE);  //显示发送验证码按钮
                layoutCountdown.setVisibility(View.GONE);   //隐藏倒计时
                txtCountdown.setText(String.valueOf(60));
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("用户登录");
        txtMobile = findViewById(R.id.txtMobile);
        txtVcode = findViewById(R.id.txtVcode);
        btnSendVcode = findViewById(R.id.btnSendVcode);
        layoutCountdown = findViewById(R.id.layoutCountdown);
        txtCountdown = findViewById(R.id.txtCountdown);
        cbAgree = findViewById(R.id.cbAgree);
        btnLogin = findViewById(R.id.btnLogin);


        //发送短信验证码
        btnSendVcode.setOnClickListener(view -> {
            if (txtMobile.getText().toString().equals("")) {
                Toast.makeText(context, "请输入手机号", Toast.LENGTH_SHORT).show();
                return;
            }
            ProgressDialog progressDialogSendVcode = ProgressDialog.show(this, "", "请稍等...");
            Thread thread = new Thread(() -> {
                String jsonString = HttpUtils.post("/api/sms/send?mobile=" + txtMobile.getText().toString(), null);
                JSONObject jsonResponse = JSONObject.parseObject(jsonString);
                if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                    //短信发送成功
                    handler.post(() -> {
                        progressDialogSendVcode.dismiss();
                        btnSendVcode.setVisibility(View.GONE);  //隐藏发送验证码按钮
                        layoutCountdown.setVisibility(View.VISIBLE);   //显示倒计时
                        handler.post(reSendVcodeCountdownRunnable);
                        Toast.makeText(context, jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    });
                } else {
                    handler.post(() -> {
                        progressDialogSendVcode.dismiss();
                        Toast.makeText(context, jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    });
                }
            });
            thread.start();
        });

        //同意复选框切换事件
        cbAgree.setOnCheckedChangeListener((compoundButton, checked) -> {
            btnLogin.setEnabled(checked);
            btnLogin.setBackgroundResource(checked ? R.color.primary : R.color.gray_1);
        });

        //登录事件
        btnLogin.setOnClickListener(view -> {
            if (txtMobile.getText().toString().equals("")) {
                Toast.makeText(context, "请输入手机号", Toast.LENGTH_SHORT).show();
                return;
            }
            if (txtVcode.getText().toString().equals("")) {
                Toast.makeText(context, "请输验证码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!cbAgree.isChecked()) {
                Toast.makeText(context, "请勾选并同意《用户协议》", Toast.LENGTH_SHORT).show();
                return;
            }
            //获取设备唯一编号
            String deviceId = DeviceUtils.getDeviceID();
            Log.i("设备编号", deviceId);
            ProgressDialog progressDialogLogin = ProgressDialog.show(this, "", "登录中...");
            Thread thread = new Thread(() -> {
                /*
                构建参数
                {
                  "deviceId": "string",
                  "mobile": "string",
                  "vcode": "string"
                }
                 */
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("mobile", txtMobile.getText().toString());
                jsonBody.put("vcode", txtVcode.getText().toString());
                jsonBody.put("deviceId", deviceId);
                jsonBody.put("registrationId", JPushInterface.getRegistrationID(this));
                Log.i("注册数据", jsonBody.toJSONString());
                String jsonString = HttpUtils.post("/api/login", jsonBody.toJSONString());
                JSONObject jsonResponse = JSONObject.parseObject(jsonString);
                if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                    //登录验证成功
                    handler.post(() -> {
                        Toast.makeText(context, jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                        User user = jsonResponse.getObject("value", User.class);    //从json中直接获取user对象
                        Log.i("登录后获取的用户", user.toString());
                        progressDialogLogin.dismiss();
                        Intent intent = new Intent();
                        intent.putExtra("user", user);
                        setResult(1, intent);
                        finish();
                    });
                } else {
                    handler.post(() -> {
                        progressDialogLogin.dismiss();
                        Toast.makeText(context, jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                    });
                }
            });
            thread.start();
        });

    }
}